import { config } from '../config'
import model from '../plugins/model'
import { logout } from '../utils/login'
import constant from '../utils/constant'

// 全局请求头，用于方法判断
let reqHeader;

const request = ({ url, method="GET", data, header = {},timeout })=> {
	reqHeader = header;
	const isToken = (reqHeader || {}).isToken === false
	if (!isToken) {
	  // 让每个请求携带自定义token
    const token = wx.getStorageSync(constant.TOKEN)
		reqHeader['Authorization'] = 'Ticket ' + token
	}
	reqHeader['Content-Type'] = 'application/json;charset=utf-8'
	reqHeader['x-sys-type'] = 'app'
	reqHeader['x-source']	=	'wx'
	let _data = {}
	if(data){
		if(data === 'object'){
			_data = JSON.stringify(data)
		}else{
			_data = data
		}
	}

  //then 正确, catch 错误
  return new Promise((resolve, reject) => {
		if(config().active == 'prod' && config().envid!=''){
			//云托管
      reqHeader['X-WX-SERVICE']	=	config().appInfo.service;
      wx.cloud.callContainer({
        config: {
          env: config().envid,
        },
        path: url,
        header: headers,
				method,
				timeout,
        data: _data,
        success: (result) => {
          hanldeSuccess(result, resolve, reject);
        },
        fail: (res) => {
          hanldeFail(res, resolve, reject);
        }
			});
			
		}else{
      let _url = url;
      if (url.indexOf("http") !== 0) {
        _url = config().baseUrl + url
      }

			wx.request({
				url: _url,
				data: _data,
				enableCache: true,
				enableHttp2: true,
				enableQuic: true,
				header: reqHeader,
				method: method,
				timeout,
				success: (result) => {
          console.log('success')
					hanldeSuccess(result, resolve, reject);
				},
				fail: (res) => {
          console.log('fail')
					hanldeFail(res, resolve, reject);
				},
				complete: (res) => {},
			});
		}
  });
};

const hanldeSuccess = (res, resolve, reject) =>{
  const statusCode = res.statusCode
	const status = res.data.status || 200
  const code = res.data.code || 0
  if(statusCode == 401 || status === 401){
    logout();
    setTimeout(() => {
      wx.navigateTo({
        url: config().unRegJumpPath,
      })
    })
  }else{
    if(reqHeader.allData){
      // 返回所有数据包括code
      resolve(res.data)
    }else{
      if(code === 0){
        // 直接返回有效数据
			  resolve(res.data.data)
      }else{
			  model.msg(res.data.msg)
		  }
    }
  }

};

// 请求失败处理
const hanldeFail = (result, resolve, reject) => {
  wx.showToast({
    title: "服务器异常，请稍后重试",
    icon: "none",
  });
  reject(result);
};

export default request;

export function upload({url, file, data, header = {}}){
  let _url = url;
  if (url.indexOf("http") !== 0) {
    _url = config().baseUrl + url
  }
  if(data == undefined){
    data = {
      oss: ''
    }
  }
  if(data.oss == undefined){
    data.oss = ''
  }
  const token = wx.getStorageSync(constant.TOKEN)
  let _header = header;
  _header['Authorization'] = 'Ticket ' + token
	// rheader['Content-Type'] = 'application/json;charset=utf-8'
	_header['x-sys-type'] = 'app'
	_header['x-source']	=	'wx'
	return new Promise((resolve, reject)=>{
		wx.uploadFile({
			name: 'file',
			header: _header,
      url: _url,
			filePath: file,
      formData: data,
			success: res=>{
				if(res.statusCode == 200){
					const resData = JSON.parse(res.data)
					const msg = resData.msg
					if(resData.code == 0){
						resolve(resData.data)
					}else{
						model.msg(msg)
					}
					
				}else{
					model.msg('上传失败')
				}
			},
			fail: err =>{
				console.log(err)
				//model.msg('上传失败')
			}
		})
	})
}